package com.xmy.cultivate.controller;

import com.aliyun.facebody20191230.models.AddFaceResponse;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.xmy.cultivate.entity.*;
import com.xmy.cultivate.entity.views.AiSitePcLoginRs;
import com.xmy.cultivate.entity.views.IntegralStatisticsRs;
import com.xmy.cultivate.entity.views.face.FaceGetScheduling;
import com.xmy.cultivate.feign.WecharFeignClient;
import com.xmy.cultivate.feign.english.IFeiEnglishFeignClient;
import com.xmy.cultivate.mapper.StudentGradeMapper;
import com.xmy.cultivate.respons.ResStudentClassType;
import com.xmy.cultivate.service.*;
import com.xmy.cultivate.util.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.amqp.AmqpException;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessagePostProcessor;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Lazy;
import org.springframework.context.annotation.Scope;
import org.springframework.web.bind.annotation.*;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.text.ParseException;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/api/test")
@Slf4j
@Scope("prototype")
public class TestController extends BaseController{

    @Value("${aliyun.AccessKeyID}")
    String accessKeyId;
    @Value("${aliyun.AccessKeySecret}")
    String accessKeySecret;
    @Value("${aliyun.oss.endpoint}")
    String ossEndpoint;
    @Value("${aliyun.oss.showImgEndpoint}")
    String showImgEndpoint;


    @Value("${uploadFile.resourceHandler}")
    private String resourceHandler;//请求 url 中的资源映射，不推荐写死在代码中，最好提供可配置，如 /uploadFiles/**
    @Value("${uploadFile.location}")
    private String uploadFileLocation;//上传文件保存的本地目录，使用@Value获取全局配置文件中配置的属性值，如 E:/wmx/uploadFiles/
    @Autowired
    @Lazy
    IStudentService iStudentService;
    @Autowired
    @Lazy
    IAliyunFaceService iAliyunFaceService;
    @Autowired
    @Lazy
    IOssUploadService iOssUploadService;
    @Autowired
    @Lazy
    IStudentFaceDataService iStudentFaceDataService;
    @Autowired
    @Lazy
    IStudentSignInService iStudentSignInService;
    @Autowired
    @Lazy
    IStudentSignInTempService iStudentSignInTempService;
    @Autowired
    @Lazy
    IFaceDbService iFaceDbService;
    @Autowired
    @Lazy
    IOrganizationService iOrganizationService;

    @Autowired
    @Lazy
    IWecharsBindService iWecharsBindService;
    @Autowired
    @Lazy
    IFaceStudentService iFaceStudentService;
    @Autowired
    @Lazy
    IRecordCourseService iRecordCourseService;
    @Autowired
    @Lazy
    WecharFeignClient testFeignClient;
    @Autowired
    IdWorker idWorker;

    @Autowired
    @Lazy
    ICourseService iCourseService;

    @Autowired
    @Lazy
    IStudentGradeService iStudentGradeService;

    @Autowired
    @Lazy
    IFeiEnglishFeignClient iFeiEnglishFeignClient;

    @Autowired
    @Lazy
    IGradeService iGradeService;

    @Autowired
    @Lazy
    StudentGradeMapper studentGradeMapper;

    @Autowired
    IQuarterService iQuarterService;

    @Autowired
    ICourseSchedulingService iCourseSchedulingService;

    @Autowired
    @Lazy
    private RabbitTemplate rabbitTemplate;

    @Autowired
    @Lazy
    private IMqPushService iMqPushService;

    @GetMapping("/getVersion")
    public Result getVersion(){
        String version = "1.0.1";
        return new Result(Code.OK,version,"当前版本号");
    }

    @GetMapping()
    public Result index() throws InterruptedException {




        //LocalDateTime localDateTime = LocalDateTime.now().withNano(0);
        //System.out.println("localDateTime:"+localDateTime);

        String str = "";
        //String str = "普通属性:"+(index++)+"....."+"静态属性："+(indexStatic++);
        System.out.println(str);

        /**
         * 报读相差多少个季度
         */
        //Integer diffNum = CommonUtil.diffQuarter(quarterMap);


        return new Result(200,str,"");

    }

    @GetMapping("explodeExl")
    public void explodeExl() throws IOException {
        Workbook wb = new XSSFWorkbook();
        Sheet sheet = wb.createSheet();
        String [] titles = "ID,名称".split(",");
        //处理标题
        Row row = sheet.createRow(0);
        int titleIndex=0;
        for (String title : titles) {
            Cell cell = row.createCell(titleIndex++);
            cell.setCellValue(title);
        }

        List<Course> courseList = iCourseService.list();
        Cell cell= null;
        int rowIndex = 1;
        for (Course course:courseList){
            row =sheet.createRow(rowIndex++);
            cell =row.createCell(0);
            cell.setCellValue(course.getId().toString());
            cell =row.createCell(1);
            cell.setCellValue(course.getName());
        }
        //3.完成下载
        ByteArrayOutputStream os = new ByteArrayOutputStream();
        wb.write(os);
        new DownloadUtils().download(os,response,"1.xlsx");
    }

    /**
     * 签到测试
     * @param map
     * @return
     */
    @GetMapping("/signIn")
    public Result  signIn(@RequestParam Map<String,Object> map){
        Long schoolId = Long.parseLong(map.get("schoolId").toString()); //1600459215889801217L;
        Long studentId = Long.parseLong(map.get("studentId").toString()); //1635269467573321728L;

        Quarter quarter = iQuarterService.getNowQuarter();

        Student student = iStudentService.getById(studentId);
        Map<String,Object> mapResult = new HashMap<>();

        /**
         * 获取排课信息
         */
        FaceGetScheduling faceGetScheduling = iFaceStudentService.getCourseSchedulingDetail(schoolId,0L,studentId,"1",1,quarter);

        //System.out.println("=========================================");
        //System.out.println(faceGetScheduling);
        if (faceGetScheduling == null || faceGetScheduling.getStatus() == null){
            mapResult.put("signCode","10003");
            return new Result(Code.FACE_ERROR,mapResult,"没有找到现在要签到的排课信息");
        }
        //mapResult.put("gradeName",faceGetScheduling.getGradeName());

        //1签到，2是签退
        Integer signType = 1;
        String courseTypeName = "";
        if (faceGetScheduling.getCourseType().equals(3)){
            //courseTypeName = "补课：";
        }else if (faceGetScheduling.getCourseType().equals(4)){
            //courseTypeName = "调课：";
        }else if (faceGetScheduling.getCourseType().equals(5)){
            //courseTypeName = "消课：";
        }

        //type:1签到，2签退，3已签到，，4已签退，5还未到签到时间，6还未到签退时间,7超过签退时间
        if(faceGetScheduling.getType().equals(1) && faceGetScheduling.getStatus().equals(1)){
            signType = 1;
            //添加到记上课表里
            /*if(faceGetScheduling.getCourseType().equals(1)){
                iRecordCourseService.addForSchedulingId(faceGetScheduling.getSchedulingDetailId(),student.getId(),1,faceGetScheduling.getCourseType());
            }*/
            //iRecordCourseService.addForSchedulingId(faceGetScheduling.getSchedulingDetailId(),student.getId(),student.getName(),1,faceGetScheduling.getCourseType());
        }else if(faceGetScheduling.getType().equals(2) && faceGetScheduling.getStatus().equals(1)){
            signType = 2;
            /*if(faceGetScheduling.getCourseType().equals(1)) {
                iRecordCourseService.addForSchedulingId(faceGetScheduling.getSchedulingDetailId(), student.getId(), 1,faceGetScheduling.getCourseType());
            }*/
            //iRecordCourseService.addForSchedulingId(faceGetScheduling.getSchedulingDetailId(), student.getId(),student.getName(),1,faceGetScheduling.getCourseType());
        }else if(faceGetScheduling.getType().equals(3) && faceGetScheduling.getStatus().equals(1)){
            //return;
            mapResult.put("signCode","10004");
            return new Result(Code.FACE_ERROR,mapResult,courseTypeName+faceGetScheduling.getGradeName()+"，今日已经刷脸签到，不要重复刷脸");
        }else if(faceGetScheduling.getType().equals(4) && faceGetScheduling.getStatus().equals(1)){
            mapResult.put("signCode","10005");
            return new Result(Code.FACE_ERROR,mapResult,courseTypeName+faceGetScheduling.getGradeName()+"，今日已经刷脸签退，不要重复刷脸");
        }else if(faceGetScheduling.getType().equals(5) && faceGetScheduling.getStatus().equals(1)){
            mapResult.put("signCode","10006");
            return new Result(Code.FACE_ERROR,mapResult,courseTypeName+faceGetScheduling.getGradeName()+"，还未到签到时间");
        }else if(faceGetScheduling.getType().equals(6) && faceGetScheduling.getStatus().equals(1)){
            mapResult.put("signCode","10006");
            return new Result(Code.FACE_ERROR,mapResult,courseTypeName+faceGetScheduling.getGradeName()+"，还未到签退时间");
        }else if(faceGetScheduling.getType().equals(7) && faceGetScheduling.getStatus().equals(1)){
            mapResult.put("signCode","10006");
            return new Result(Code.FACE_ERROR,mapResult,courseTypeName+faceGetScheduling.getGradeName()+"，超过签退时间");
        }else{
            mapResult.put("signCode","10006");
            return new Result(Code.FACE_ERROR,mapResult,courseTypeName+faceGetScheduling.getGradeName()+"，今日已经刷脸签到和签退，不要重复刷脸");
        }

        //1签到，2是签退
        mapResult.put("signType",signType);


        StudentSignIn studentSignIn = new StudentSignIn();
        studentSignIn.setId(faceGetScheduling.getSignInId());
        studentSignIn.setSchoolId(schoolId);
        studentSignIn.setStudentId(student.getId());
        studentSignIn.setStudentName(student.getName());
        studentSignIn.setSubjectsId(faceGetScheduling.getSubjectsId());
        studentSignIn.setSchedulingDetailId(faceGetScheduling.getSchedulingDetailId());
        studentSignIn.setId(faceGetScheduling.getSignInId());
        studentSignIn.setCourseType(faceGetScheduling.getCourseType());
        LocalDate localDate = LocalDate.now();
        LocalDateTime localDateTime = LocalDateTime.now().withNano(0);

        if(signType.equals(1)){
            studentSignIn.setInDateTime(localDateTime);
        }else {
            studentSignIn.setOutDateTime(localDateTime);
        }

        studentSignIn.setAddDate(localDate);
        studentSignIn.setCreatedAt(localDateTime);
        studentSignIn.setType(signType);
        //studentSignIn.setType();
        iStudentSignInService.saveOrUpdate(studentSignIn);

        //添加到临时表，为了记上课查询用
        iStudentSignInTempService.saveOrUpdateDataCustom(studentSignIn);

        if(signType.equals(1)){
            mapResult.put("signCode","10001");
            return new Result(Code.OK,mapResult,courseTypeName+faceGetScheduling.getGradeName()+"，签到成功");
        }else {
            mapResult.put("signCode","10002");
            return new Result(Code.OK,mapResult,courseTypeName+faceGetScheduling.getGradeName()+"，签退成功");
        }
    }

    /**
     * 人脸采集
     * @return
     */
    @PostMapping("/faceGather")
    public Result faceGather(@RequestBody Map<String,Object> repMap)throws Exception{
        String schoolId = "";
        String studentId = "";

        Organization schoolInfo = null;
        if(StringUtils.isEmpty(schoolId)){
            return new Result(Code.ERROR,"","学校id不能为空");
        }else {
            schoolInfo = iOrganizationService.getById(schoolId);
            if(schoolInfo == null){
                return new Result(Code.ERROR,"","学校不存在");
            }
        }
        if(StringUtils.isEmpty(studentId)){
            return new Result(Code.ERROR,"","学生id不能为空");
        }
        Student student = iStudentService.getById(studentId);
        if(student == null){
            return new Result(Code.ERROR,"","学生不存在");
        }
        LocalDate localDate = LocalDate.now();

        Map<String,Object> mapResult = new HashMap<>();

        FaceDb faceDb = iFaceDbService.getFaceDbOne(1);

        //上传文件的位置,默认会在项目根目录找static文件夹,需手动创建,不然找到是临时路径。
        //String path = request.getSession().getServletContext().getRealPath("/uploads/"+directoryName);
        //System.out.println("path:"+path);
        //判断该路径是否存在
        String directoryName = "face-gather/2023-1";
        String filename = "2023011675155413930.jpg";

        // 完成文件上传
        try {
            String ossImageUrl = "https://xmy-face.oss-cn-shanghai.aliyuncs.com/face-gather/2023-1/2023011675155413930.jpg";
            String faceIdAndentityId = iAliyunFaceService.searchFaceReturnEntityId(faceDb.getDbName(),Long.parseLong(schoolId),ossImageUrl);
            if(faceIdAndentityId !=null && !faceIdAndentityId.equals("error")){
                String[] faceIdAndEntityIdArr = faceIdAndentityId.split(",");
                String faceId = faceIdAndEntityIdArr[0];
                String entityId = faceIdAndEntityIdArr[1];
                if(studentId != entityId){
                    //修改学生状态
                    student.setHeadImg(ossImageUrl);
                    student.setIsGather(1);
                    student.setEntityId(entityId);
                    iStudentService.updateById(student);

                    QueryWrapper<StudentFaceData> studentFaceDataQueryWrapper = new QueryWrapper<>();
                    studentFaceDataQueryWrapper.eq("school_id",schoolId);
                    studentFaceDataQueryWrapper.eq("student_id",student.getId());
                    studentFaceDataQueryWrapper.eq("entity_id",entityId);
                    studentFaceDataQueryWrapper.last("limit 1");
                    StudentFaceData studentFaceData = iStudentFaceDataService.getOne(studentFaceDataQueryWrapper);

                    StudentFaceData studentFaceDataAdd = new StudentFaceData();
                    studentFaceDataAdd.setSchoolId(Long.parseLong(schoolId));
                    studentFaceDataAdd.setStudentId(student.getId());
                    studentFaceDataAdd.setEntityId(Long.parseLong(entityId));
                    studentFaceDataAdd.setOssImage(ossImageUrl);
                    studentFaceDataAdd.setImage(directoryName+"/"+filename);
                    if(studentFaceData !=null){
                        studentFaceDataAdd.setFaceId(studentFaceData.getFaceId());
                        studentFaceDataAdd.setQualitieScore(studentFaceData.getQualitieScore());
                    }else {
                        studentFaceDataAdd.setFaceId(faceId);
                    }
                    iStudentFaceDataService.save(studentFaceDataAdd);
                    mapResult.put("signCode","10001");
                    return new Result(Code.OK,mapResult,"人脸采集成功");
                }
            }else if(faceIdAndentityId !=null && faceIdAndentityId.equals("error")){
                mapResult.put("signCode","10002");
                return new Result(Code.FACE_ERROR,mapResult,"人脸采集失败,请重新采集");
            }

            if(iAliyunFaceService.existFaceSample(Long.parseLong(schoolId),faceDb.getDbName(),student.getId().toString())){
                iAliyunFaceService.updateFaceSample(Long.parseLong(schoolId),faceDb.getDbName(),student.getId().toString(),student.getName());//添加人脸样本
            }else {
                iAliyunFaceService.addFaceSample(Long.parseLong(schoolId),faceDb.getDbName(),student.getId().toString(),student.getName());//添加人脸样本
            }

            student.setIsGather(1);//设置为已采集
            QueryWrapper<StudentFaceData> studentFaceDataQueryWrapper = new QueryWrapper<>();

            studentFaceDataQueryWrapper.eq("school_id",schoolId);
            studentFaceDataQueryWrapper.eq("student_id",student.getId());
            studentFaceDataQueryWrapper.eq("entity_id",student.getId());
            studentFaceDataQueryWrapper.orderByAsc("created_at");
            List<StudentFaceData> studentFaceDataList = iStudentFaceDataService.list(studentFaceDataQueryWrapper);

            AddFaceResponse addFaceResponse =null;
            String extraData = student.getName().trim();
            if(studentFaceDataList.size()>=5){
                StudentFaceData studentFaceData = studentFaceDataList.get(0);
                studentFaceData.getEntityId();
                if(studentFaceData.getFaceId() !=null){
                    iAliyunFaceService.delFaceData(Long.parseLong(schoolId),faceDb.getDbName(),studentFaceData.getFaceId().toString());
                    iStudentFaceDataService.removeById(studentFaceData.getId());
                    addFaceResponse = iAliyunFaceService.addFaceData(Long.parseLong(schoolId),faceDb.getDbName(),ossImageUrl,student.getId().toString(),extraData,1);//添加人脸数据
                    //System.out.println("addFaceResponse2");
                    //System.out.println(addFaceResponse);
                }
            }else {
                addFaceResponse = iAliyunFaceService.addFaceData(Long.parseLong(schoolId),faceDb.getDbName(),ossImageUrl,student.getId().toString(),extraData,1);//添加人脸数据
                //System.out.println("addFaceResponse");
                //System.out.println(addFaceResponse);
            }
            if(addFaceResponse !=null && addFaceResponse.getBody() !=null && addFaceResponse.getBody().getData() != null){
                StudentFaceData studentFaceData = new StudentFaceData();
                studentFaceData.setSchoolId(Long.parseLong(schoolId));
                studentFaceData.setStudentId(student.getId());
                studentFaceData.setEntityId(student.getId());
                studentFaceData.setOssImage(ossImageUrl);
                studentFaceData.setFaceId(addFaceResponse.getBody().getData().faceId);
                studentFaceData.setQualitieScore(addFaceResponse.getBody().getData().qualitieScore);
                studentFaceData.setImage(directoryName+"/"+filename);
                iStudentFaceDataService.save(studentFaceData);

                //修改学生状态
                student.setHeadImg(ossImageUrl);
                student.setIsGather(1);
                student.setEntityId(student.getId().toString());
                iStudentService.updateById(student);
                mapResult.put("signCode","10001");
                return new Result(Code.OK,mapResult,"人脸采集成功");
            }else {
                if(addFaceResponse !=null && addFaceResponse.getStatusCode() == 50000){
                    mapResult.put("signCode","10002");
                    return new Result(Code.FACE_ERROR,"","人脸采集失败,重新采集");
                }else {
                    mapResult.put("signCode","10002");
                    return new Result(Code.FACE_ERROR,"","人脸采集失败,重新采集（没有采集到数据）");
                }
            }
        } catch (Exception e) {
            //System.out.println("singCodeError");
            //System.out.println(e.getMessage());
            e.printStackTrace();
            mapResult.put("signCode","50000");
            return new Result(Code.FACE_ERROR,mapResult,"人脸采集失败（数据异常）");
        }
    }

    @GetMapping("/getId")
    public Result getId(){
        Long id = idWorker.nextId();
        return new Result(Code.OK,id,"");
    }

    @GetMapping("/delFaceSampleForEntityId")
    public Result delFaceSampleForEntityId(@RequestParam("schoolId") Long schoolId,@RequestParam("studentId") Long studentId) throws Exception {
        FaceDb faceDb = iFaceDbService.getFaceDbOne(1);

        Long entityId = studentId;
        boolean rs = iAliyunFaceService.delFaceSampleForEntityId(schoolId, faceDb.getDbName(), entityId.toString());
        if (rs){
            return new Result(Code.OK,"","删除成功");
        }else {
            return new Result(Code.ERROR,"","删除失败");
        }
    }

    @GetMapping("/delFaceDataForFaceId")
    public Result delFaceDataForFaceId(@RequestParam("schoolId") Long schoolId,@RequestParam("faceId") Long faceId) throws Exception {
        FaceDb faceDb = iFaceDbService.getFaceDbOne(1);

        boolean rs = iAliyunFaceService.delFaceData(schoolId, faceDb.getDbName(), faceId.toString());
        if (rs){
            return new Result(Code.OK,"","删除成功");
        }else {
            return new Result(Code.ERROR,"","删除失败");
        }
    }

    @GetMapping("/addStudentFaceDb")
    public Result addStudentFaceDb(@RequestParam("schoolId") Long schoolId,
                                   @RequestParam("studentId") Long studentId) throws Exception{

        QueryWrapper<StudentFaceData> studentFaceDataQueryWrapper = new QueryWrapper<>();
        studentFaceDataQueryWrapper.eq("school_id", schoolId);
        studentFaceDataQueryWrapper.eq("update_level", 0);
        studentFaceDataQueryWrapper.eq("student_id", studentId);

        //studentFaceDataQueryWrapper.groupBy("student_id");

        Integer rightCount = 0;
        Integer errorCount = 0;
        Integer index = 0;
        List<StudentFaceData> studentFaceDataList = iStudentFaceDataService.list(studentFaceDataQueryWrapper);
        //System.out.println("studentFaceDataList:" + studentFaceDataList.size());
        for (StudentFaceData studentFaceData : studentFaceDataList) {
            boolean rs = this.setData(studentFaceData.getSchoolId(), studentFaceData.getStudentId().toString(), studentFaceData.getOssImage(), studentFaceData);
            if (rs) {
                rightCount++;
            } else {
                errorCount++;
            }
            Thread.sleep(500);
            index++;
        }
        return new Result(Code.OK,"","添加成功");
    }

    /**
     * 添加人脸数据
     *
     * @param schoolId
     * @param studentId
     * @param ossImageUrl
     * @param studentFaceDataOld
     * @return
     * @throws Exception
     */
    private boolean setData(Long schoolId, String studentId, String ossImageUrl, StudentFaceData studentFaceDataOld) throws Exception {

        FaceDb faceDb = iFaceDbService.getFaceDbOne(1);

        Student student = iStudentService.getById(studentId);

        String faceIdAndentityId = iAliyunFaceService.searchFaceReturnEntityId(faceDb.getDbName(), schoolId, ossImageUrl);
        if (faceIdAndentityId != null && !faceIdAndentityId.equals("error")) {

            String[] faceIdAndEntityIdArr = faceIdAndentityId.split(",");
            String faceId = faceIdAndEntityIdArr[0];
            String entityId = faceIdAndEntityIdArr[1];
            if (studentId != entityId) {
                student.setIsGather(1);
                student.setEntityId(entityId);
                iStudentService.updateById(student);
                studentFaceDataOld.setFaceId(faceId);
                studentFaceDataOld.setEntityId(Long.parseLong(entityId));
                studentFaceDataOld.setUpdateLevel(1);
                iStudentFaceDataService.updateById(studentFaceDataOld);
                return true;
            }
        } else if (faceIdAndentityId != null && faceIdAndentityId.equals("error")) {
            return false;
        }

        if (iAliyunFaceService.existFaceSample(schoolId, faceDb.getDbName(), student.getId().toString())) {
            iAliyunFaceService.updateFaceSample(schoolId, faceDb.getDbName(), student.getId().toString(), student.getName());//添加人脸样本
        } else {
            iAliyunFaceService.addFaceSample(schoolId, faceDb.getDbName(), student.getId().toString(), student.getName());//添加人脸样本
        }
        student.setIsGather(1);//设置为已采集
        QueryWrapper<StudentFaceData> studentFaceDataQueryWrapper = new QueryWrapper<>();

        String extraData = student.getName().trim();
        AddFaceResponse addFaceResponse = iAliyunFaceService.addFaceData(schoolId, faceDb.getDbName(), ossImageUrl, student.getId().toString(), extraData,1);//添加人脸数据


        if (addFaceResponse != null && addFaceResponse.getBody() != null && addFaceResponse.getBody().getData() != null) {
            studentFaceDataOld.setEntityId(studentFaceDataOld.getStudentId());
            studentFaceDataOld.setFaceId(addFaceResponse.getBody().getData().faceId);
            studentFaceDataOld.setQualitieScore(addFaceResponse.getBody().getData().qualitieScore);
            studentFaceDataOld.setUpdateLevel(1);
            iStudentFaceDataService.updateById(studentFaceDataOld);
            System.out.println("采集成功,faceId:" + studentFaceDataOld.getFaceId());
            return true;
        } else {
            if (addFaceResponse != null && addFaceResponse.getStatusCode() == 50000) {
                return false;
            } else {
                return false;
            }
        }
    }

    /**
     * 额外排课
     * @return
     * @throws ParseException
     */
    @GetMapping("/addScheduling")
    public Result addScheduling(@RequestParam("yearPart") Integer yearPart,
                                @RequestParam("quarterNum") Integer quarterNum,
                                @RequestParam("lessonType") Integer lessonType,
                                @RequestParam("startDate") String startDate,
                                @RequestParam("endDate") String endDate
                                ) throws ParseException {
        iCourseSchedulingService.addOtherDate(yearPart,quarterNum,lessonType,startDate,endDate);
        return new Result(Code.OK,"","发送成功");
    }

    /**
     * 延迟消息
     * @return
     */
    @GetMapping("/mqTest")
    public Result mqTest(){
        // 1.创建消息
        String message = "hello, delayed message";

        Student student = new Student();
        student.setName("测试");
        student.setId(idWorker.nextId());
        student.setCreatedAt(LocalDateTime.now().withNano(0));

        // 2.发送消息，利用消息后置处理器添加消息头
        rabbitTemplate.convertAndSend("delay.direct", "delay", student, new MessagePostProcessor() {
            @Override
            public Message postProcessMessage(Message message) throws AmqpException {
                // 添加延迟消息属性
                message.getMessageProperties().setDelay(10000);
                return message;
            }
        });

        return new Result(Code.OK,"","发送成功");
    }

    @PostMapping("/delFaceDataForAccount")
    public Result delFaceDataForAccount(@RequestBody Organization schoolInfo) throws Exception {
        String dbName = schoolInfo.getName();
        QueryWrapper<Organization> organizationQueryWrapper = new QueryWrapper<>();
        organizationQueryWrapper.eq("type", 1);
        organizationQueryWrapper.eq("status", 1);
        organizationQueryWrapper.eq(StringUtils.isNotBlank(schoolInfo.getAliAccount()),"ali_account",schoolInfo.getAliAccount());
        organizationQueryWrapper.groupBy("ali_account");
        List<Organization> organizationList = iOrganizationService.list(organizationQueryWrapper);
        for (Organization organization : organizationList) {
            if (dbName!=null){
                iAliyunFaceService.getFaceEntitiesList(organization.getId(),dbName);
            }else {
                iAliyunFaceService.getFaceEntitiesList(organization.getId(),"default");
            }
        }
        return new Result(Code.OK,"","删除中");
    }

    @PostMapping("/integralStatistics")
    public Result integralStatistics(@RequestBody IntegralStatisticsRs integralStatisticsRs){
        iMqPushService.integralStatistics(integralStatisticsRs);
        return new Result(Code.OK,"","重新计算中……");
    }


    @PostMapping("/testAllotMq")
    public Result testAllotMq(AiSitePcLoginRs aiSitePcLoginRs){
        /*AiSitePcLoginRs aiSitePcLoginRs = new AiSitePcLoginRs();
        //aiSitePcLoginRs.setSchoolId();
        aiSitePcLoginRs.setSchoolSiteId(schoolSiteId);
        aiSitePcLoginRs.setYearPart(quarterNow.getYearPart());
        aiSitePcLoginRs.setQuarterNum(quarterNow.getNum());
        aiSitePcLoginRs.setStudentId(student.getId());
        aiSitePcLoginRs.setStudentName(student.getName());
        aiSitePcLoginRs.setUserId(this.adminId);*/
        iMqPushService.allotPc(aiSitePcLoginRs);
        return new Result(Code.OK,"","发送成功……");
    }

    /**
     * 测试签到推送分班
     * @return
     */
    @PostMapping("/testAllot")
    public Result testAllot(@RequestBody AiSitePcLoginRs aiSitePcLoginRs){
        Student student = iStudentService.getById(aiSitePcLoginRs.getStudentId());
        aiSitePcLoginRs.setStudentName(student.getName());
        iMqPushService.allotPc(aiSitePcLoginRs);
        return new Result(Code.OK,"","分电脑中……");
    }

}
